package com.ljkj.cordial.chat.notify;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.ChatMainActivity;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.util.SharedUserUtils;

/**
 * @description:
 * @author: Panwei
 * @date: 2020/1/16 19:50
 */
public class NotificationUtils {
    private static String mNotificationGroupId = "cordial_notification_group";
    private static NotificationManager mNotificationManager;
    private static String mTargetId;

    private static NotificationManager getNotificationManager(Context context) {
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(mNotificationGroupId, context.getString(R.string.app_name)));
        }
        return mNotificationManager;
    }

    public static void notify(Context context, Notify notify, String tag) {
        boolean is_r = (boolean) SharedUserUtils.get(context, Canstants.KEY_SYS_IS_MESSAGE_TONE, true);

        Intent intent = new Intent(context, ChatMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Canstants.NOTIFY_KEY_FROM, !notify.content.contains("同意"));
        intent.putExtra(Canstants.NOTIFY_KEY_IS_CHAT, notify.notify != 1);
        intent.putExtra(Canstants.NOTIFY_KEY_TYPE, notify.type);
        intent.putExtra(Canstants.NOTIFY_KEY_TARGET_NAME, notify.name);
        intent.putExtra(Canstants.NOTIFY_KEY_TARGET_ID, notify.id);
        intent.putExtra(Canstants.NOTIFY_KEY_TARGET_TYPE, IMSContacts.UserType.REGISTERED_USER);

        String channelId = context.getPackageName();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setSound(null, null);
            notificationChannel.setGroup(mNotificationGroupId);
            getNotificationManager(context).createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.icon_notify_app)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_green_app))
                .setContentTitle(notify.title)
                .setContentText(notify.content)
                .setTicker(context.getString(R.string.app_name))
                .setContentIntent(PendingIntent.getActivity(context, NotificationHelper.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT))
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setGroupSummary(true)
                .setGroup(mNotificationGroupId)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setDefaults(Notification.DEFAULT_ALL)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setChannelId(channelId)
                .setSound(null);    // 关闭Notification自带的提示音，声音自己维护
        if (notify.notify == 1)
            builder.setTimeoutAfter(2000L);
        getNotificationManager(context).notify(tag, notify.id, builder.build());
        if (is_r) {
            PromptTone.ring(context);
        }
    }

    @Deprecated
    public static void messageNotify(Context context) {
//        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Integer>() {
//            @Override
//            public void onAction(Integer obj) {
//                NotificationUtils.notify(context, obj);
//            }
//
//            @Override
//            public Integer onThreadAction() {
//                long count1 = DbController.getInstance().getRead().getBusinessLeaveTableDao().queryBuilder().where(BusinessLeaveTableDao.Properties.IsRead.eq(0), BusinessLeaveTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).count();
//                long count2 = ChatContentTable.getUnReadChatSum(ChatContentTable.queryList());
//                return (int) (count1 + count2);
//            }
//        });
    }

    public static void notifyFriend(Context context, FriendTable friend, int type) {
        if (friend == null || TextUtils.isEmpty(friend.getFriendUserId())) return;
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Notify>() {
            @Override
            public void onAction(Notify obj) {
                if (obj != null && !TextUtils.isEmpty(obj.content)) {
                    NotificationUtils.notify(context, obj, NotificationHelper.TAG_SINGLE);
                }
            }

            @Override
            public Notify onThreadAction() {
                Notify notify = new Notify();
                notify.id = NotificationUtils.getNotificationId(friend.getFriendUserId());
                if (notify.id == -1) return null;
                FriendTable friendFromSql = FriendTable.getTableByFriendUserId(friend.getFriendUserId());
                notify.title = NotificationUtils.getNotificationFriendTitle(friend, friendFromSql);
                notify.content = NotificationUtils.getNotificationFriendContent(type, friend.getFriendUserId());
                notify.name = NotificationUtils.getNotificationFriendName(friend, friendFromSql);
                notify.type = Canstants.SINGLE_CHAT;
                if (TextUtils.isEmpty(notify.content)) return null;
                if (type != NotificationHelper.NTYPE_FRIEND_CHAT)
                    notify.notify = 1;
                return notify;
            }
        });
    }

    public static void notifyGroup(Context context, GroupTable group, GroupMemberTable groupMember, int type) {
        if (group == null || TextUtils.isEmpty(group.getGroupId())) return;
        if (groupMember == null || TextUtils.isEmpty(groupMember.getGroupMemberUserId())) return;
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Notify>() {
            @Override
            public void onAction(Notify obj) {
                if (obj != null && !TextUtils.isEmpty(obj.content)) {
                    NotificationUtils.notify(context, obj, NotificationHelper.TAG_GROUP);
                }
            }

            @Override
            public Notify onThreadAction() {
                Notify notify = new Notify();
                notify.id = NotificationUtils.getNotificationId(group.getGroupId());
                if (notify.id == -1) return null;
                notify.title = group.getGroupName();
                String memberName = NotificationUtils.getNotificationGroupMemberName(group.getGroupId(), groupMember, GroupMemberTable.query(group.getGroupId(), groupMember.getGroupMemberUserId()));
                notify.content = NotificationUtils.getNotificationGroupContent(type, groupMember.getGroupMemberUserId(), memberName, group.getGroupName(), group.getGroupId());
                notify.name = group.getGroupName();
                notify.type = Canstants.GROUP_CHAT;
                if (TextUtils.isEmpty(notify.content)) return null;
                if (type != NotificationHelper.NTYPE_GROUP_CHAT)
                    notify.notify = 1;
                return notify;
            }
        });
    }

    public static void clearNotify(Context context) {
        getNotificationManager(context).cancelAll();
    }

    public static void clearNotify(Context context, String id, int chatType) {
        int notifyId = getNotificationId(id, false);
        if (notifyId == -1) return;
        if (Canstants.SINGLE_CHAT == chatType) {
            getNotificationManager(context).cancel(NotificationHelper.TAG_SINGLE, notifyId);
        } else if (Canstants.GROUP_CHAT == chatType) {
            getNotificationManager(context).cancel(NotificationHelper.TAG_GROUP, notifyId);
        }
    }

    public static void setupTargetId(String targetId) {
        mTargetId = targetId;
    }

    public static void removeTargetId() {
        mTargetId = "";
    }

    private static int getNotificationId(String id) {
        return getNotificationId(id, true);
    }

    private static int getNotificationId(String id, boolean flag) {
        if (flag && id.equals(mTargetId))
            return -1;
        try {
            return Integer.parseInt(id);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    private static String getNotificationFriendName(FriendTable friend, FriendTable friendFromSql) {
        if (friendFromSql == null)
            return friend.getFriendNickname();
        return friendFromSql.getFriendNickname();
    }

    private static String getNotificationFriendTitle(FriendTable friend, FriendTable friendFromSql) {
        if (friendFromSql == null)
            return friend.getFriendNickname();
        return !TextUtils.isEmpty(friendFromSql.getFriendAlias()) ? friendFromSql.getFriendAlias() : friendFromSql.getFriendNickname();
    }

    private static String getNotificationGroupMemberName(String groupId, GroupMemberTable groupMember, GroupMemberTable groupMemberFromSql) {
        if (groupMemberFromSql == null) {
            return groupMember.getGroupMemberName();
        } else {
            return !TextUtils.isEmpty(groupMemberFromSql.getGroupMemberAlias()) ? groupMemberFromSql.getGroupMemberAlias() : groupMemberFromSql.getGroupMemberName();
        }
    }

    private static String getNotificationFriendContent(int type, String friendUserId) {
        switch (type) {
            case NotificationHelper.NTYPE_FRIEND_ADD:
                return "同意了你的好友申请";
            case NotificationHelper.NTYPE_FRIEND_APPLY:
                return "申请添加好友";
            case NotificationHelper.NTYPE_FRIEND_REFUSE:
                return "拒绝了你的好友申请";
            case NotificationHelper.NTYPE_FRIEND_CHAT:
                long unReadCount = ChatTableBean.queryUnreadChatCount(Canstants.SINGLE_CHAT, friendUserId);
                if (unReadCount <= 0) {
                    return "";
                } else {
                    return String.format("发来消息 %s 条消息", String.valueOf(unReadCount));
                }
            default:
                return "";
        }
    }

    private static String getNotificationGroupContent(int type, String memberId, String memberName, String groupName, String groupId) {
        switch (type) {
            case NotificationHelper.NTYPE_GROUP_APPLY:
                return "申请加入" + groupName;
            case NotificationHelper.NTYPE_GROUP_REFUSE:
                return "拒绝了你的加群申请";
            case NotificationHelper.NTYPE_GROUP_INVITE:
                return memberName + "邀请加入了" + groupName;
            case NotificationHelper.NTYPE_GROUP_ADD:
                return "同意了你的加群申请";
            case NotificationHelper.NTYPE_GROUP_CHAT:
                long unReadCount = ChatTableBean.queryUnreadChatCount(Canstants.GROUP_CHAT, groupId);
                if (unReadCount <= 0) {
                    return "";
                } else {
                    return String.format("%s发来消息，现有 %s 条未读消息", memberName, String.valueOf(unReadCount));
                }
            case NotificationHelper.NTYPE_GROUP_DELETE:
                if (!TextUtils.isEmpty(memberId) && memberId.contains(UserPreferences.getUserId()))
                    return "你被踢出了群聊";
                else
                    return memberName + "被踢出了群聊";
            case NotificationHelper.NTYPE_GROUP_EXIT:
                return memberName + "退出了群聊";
            case NotificationHelper.NTYPE_GROUP_DISSOLVE:
                return "群主解散了该群";
            default:
                return "";
        }
    }

    private static class Notify {
        int id;
        String title;
        String content;
        int notify;
        String name;
        int type;
    }
}
